using Microsoft.Extensions.DependencyInjection;
using Models;
using Utils;

namespace Respository
{
    /// <summary>
    /// 员工考勤数据仓储类
    /// </summary>
    public class EmployeeAttendanceRepository
    {
        private readonly IServiceProvider _serviceProvider;

        public EmployeeAttendanceRepository(IServiceProvider serviceProvider)
        {
            this._serviceProvider = serviceProvider;
        }

        /// <summary>
        /// 保存员工考勤数据
        /// </summary>
        /// <param name="employeeData">员工数据</param>
        /// <returns>保存结果</returns>
        public FuncResult<int> SaveEmployeeAttendance(EmployeeData employeeData)
        {
            var result = new FuncResult<int>();
            try
            {
                var _context = this._serviceProvider.GetService<AppDbContext>();
                if (_context != null)
                {
                    var attendanceRecord = new tb_EmployeeAttendance
                    {
                        EmployeeId = employeeData.EmployeeId,
                        EmployeeName = employeeData.EmployeeName,
                        EmployeeType = employeeData.EmployeeType,
                        LoginTime = DateTime.TryParse(employeeData.LoginTime, out var loginTime) ? loginTime : null,
                        ReceiveTime = DateTime.Now,
                        Source = "KaoQinMonitor",
                        Status = "Active"
                    };

                    _context.tb_EmployeeAttendance.Add(attendanceRecord);
                    result.obj_Return = _context.SaveChanges();
                    result.bSuccess = true;
                }
                else
                {
                    result.bSuccess = false;
                    result.strMsg = "无法获取到数据库服务";
                }
            }
            catch (Exception ex)
            {
                result.setException(ex);
                result.obj_Return = 0;
            }
            return result;
        }

        /// <summary>
        /// 根据工号获取最新的考勤记录
        /// </summary>
        /// <param name="employeeId">工号</param>
        /// <returns>考勤记录</returns>
        public FuncResult<tb_EmployeeAttendance> GetLatestAttendanceByEmployeeId(string employeeId)
        {
            var result = new FuncResult<tb_EmployeeAttendance>();
            try
            {
                var _context = this._serviceProvider.GetService<AppDbContext>();
                if (_context != null)
                {
                    var record = _context.tb_EmployeeAttendance
                        .Where(e => e.EmployeeId == employeeId)
                        .OrderByDescending(e => e.ReceiveTime)
                        .FirstOrDefault();
                    
                    result.obj_Return = record;
                    result.bSuccess = true;
                }
                else
                {
                    result.bSuccess = false;
                    result.strMsg = "无法获取到数据库服务";
                }
            }
            catch (Exception ex)
            {
                result.setException(ex);
            }
            return result;
        }

        /// <summary>
        /// 获取指定时间范围内的考勤记录
        /// </summary>
        /// <param name="startTime">开始时间</param>
        /// <param name="endTime">结束时间</param>
        /// <returns>考勤记录列表</returns>
        public FuncResult<List<tb_EmployeeAttendance>> GetAttendanceByTimeRange(DateTime startTime, DateTime endTime)
        {
            var result = new FuncResult<List<tb_EmployeeAttendance>>();
            try
            {
                var _context = this._serviceProvider.GetService<AppDbContext>();
                if (_context != null)
                {
                    var records = _context.tb_EmployeeAttendance
                        .Where(e => e.ReceiveTime >= startTime && e.ReceiveTime <= endTime)
                        .OrderByDescending(e => e.ReceiveTime)
                        .ToList();
                    
                    result.obj_Return = records;
                    result.bSuccess = true;
                }
                else
                {
                    result.bSuccess = false;
                    result.strMsg = "无法获取到数据库服务";
                }
            }
            catch (Exception ex)
            {
                result.setException(ex);
            }
            return result;
        }

        /// <summary>
        /// 获取今日所有考勤记录
        /// </summary>
        /// <returns>今日考勤记录列表</returns>
        public FuncResult<List<tb_EmployeeAttendance>> GetTodayAttendance()
        {
            var today = DateTime.Today;
            var tomorrow = today.AddDays(1);
            return GetAttendanceByTimeRange(today, tomorrow);
        }

        /// <summary>
        /// 删除指定时间之前的考勤记录（用于数据清理）
        /// </summary>
        /// <param name="beforeTime">指定时间</param>
        /// <returns>删除的记录数</returns>
        public FuncResult<int> DeleteAttendanceBeforeTime(DateTime beforeTime)
        {
            var result = new FuncResult<int>();
            try
            {
                var _context = this._serviceProvider.GetService<AppDbContext>();
                if (_context != null)
                {
                    var recordsToDelete = _context.tb_EmployeeAttendance
                        .Where(e => e.ReceiveTime < beforeTime)
                        .ToList();
                    
                    _context.tb_EmployeeAttendance.RemoveRange(recordsToDelete);
                    result.obj_Return = _context.SaveChanges();
                    result.bSuccess = true;
                }
                else
                {
                    result.bSuccess = false;
                    result.strMsg = "无法获取到数据库服务";
                }
            }
            catch (Exception ex)
            {
                result.setException(ex);
                result.obj_Return = 0;
            }
            return result;
        }
    }
}
